package com.example.projectmanagement.controller;

import com.example.projectmanagement.dto.ServerStatusDto;
import com.example.projectmanagement.dto.ApiMonitorDto;
import com.example.projectmanagement.dto.SystemMetricDto;
import com.example.projectmanagement.service.SystemMonitorService;
import com.example.projectmanagement.service.ApiMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/system")
@PreAuthorize("hasRole('ADMIN')")
public class SystemStatusController {

    @Autowired
    private SystemMonitorService systemMonitorService;
    
    @Autowired
    private ApiMonitorService apiMonitorService;

    /**
     * 获取服务器状态
     */
    @GetMapping("/status")
    public ResponseEntity<ServerStatusDto> getServerStatus() {
        ServerStatusDto status = systemMonitorService.getServerStatus();
        return ResponseEntity.ok(status);
    }

    /**
     * 获取API监控信息
     */
    @GetMapping("/api-monitor")
    public ResponseEntity<ApiMonitorDto> getApiMonitor() {
        ApiMonitorDto apiMonitor = systemMonitorService.getApiMonitorInfo();
        return ResponseEntity.ok(apiMonitor);
    }

    /**
     * 刷新系统状态
     */
    @PostMapping("/refresh")
    public ResponseEntity<ServerStatusDto> refreshStatus() {
        ServerStatusDto status = systemMonitorService.getServerStatus();
        return ResponseEntity.ok(status);
    }
    
    /**
     * 重置API监控数据
     */
    @PostMapping("/api-monitor/reset")
    public ResponseEntity<String> resetApiMonitorData(@RequestParam(required = false) Integer hours) {
        if (hours != null) {
            // 根据时间重置数据
            apiMonitorService.resetApiStatsByTime(hours);
        } else {
            // 重置所有数据
            apiMonitorService.resetAllApiStats();
        }
        return ResponseEntity.ok("API监控数据已重置");
    }
    
    /**
     * 获取CPU使用率历史数据
     */
    @GetMapping("/cpu-history")
    public ResponseEntity<List<SystemMetricDto>> getCpuHistory(@RequestParam(defaultValue = "24h") String period) {
        List<SystemMetricDto> cpuHistory = systemMonitorService.getCpuHistory(period);
        return ResponseEntity.ok(cpuHistory);
    }
    
    /**
     * 获取内存使用率历史数据
     */
    @GetMapping("/memory-history")
    public ResponseEntity<List<SystemMetricDto>> getMemoryHistory(@RequestParam(defaultValue = "24h") String period) {
        List<SystemMetricDto> memoryHistory = systemMonitorService.getMemoryHistory(period);
        return ResponseEntity.ok(memoryHistory);
    }
}